// src/components/Sidebar.jsx
import { useState, useRef, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faSearch,
  faClock,
  faProjectDiagram,
  faStream,
  faTrashCan,
  faEdit
} from '@fortawesome/free-solid-svg-icons';
import { getIconByType } from '../utils/icons';

export default function Sidebar({ 
  agents, 
  workflows, 
  onLoadWorkflow,
  onDeleteAgent,
  onDeleteWorkflow,
  onConfigureAgent
}) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedType, setSelectedType] = useState('全部');
  const [activeTab, setActiveTab] = useState('agents');
  const [contextMenu, setContextMenu] = useState(null);
  const clickedItem = useRef(null);
  const menuRef = useRef(null);

  // 处理右键点击
  const handleRightClick = (e, item, type) => {
    e.preventDefault();
    clickedItem.current = { item, type };
    setContextMenu({
      x: e.clientX,
      y: e.clientY,
    });
  };

  // 处理删除操作
  const handleDelete = () => {
    if (!clickedItem.current) return;
    
    const { item, type } = clickedItem.current;
    if (type === 'agent' && window.confirm(`确定删除智能体 "${item.config.label}" 吗？`)) {
      onDeleteAgent(item.id);
    } 
    else if (type === 'workflow' && window.confirm(`确定删除工作流 "${item.name}" 吗？`)) {
      onDeleteWorkflow(item.id);
    }
    
    setContextMenu(null);
    clickedItem.current = null;
  };

  // 处理更新配置
  const handleConfigure = () => {
    if (clickedItem.current?.type === 'agent') {
      onConfigureAgent(clickedItem.current.item);
    } else {
      onLoadWorkflow(clickedItem.current.item);
    }
    setContextMenu(null);
  };

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) {
        setContextMenu(null);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // 格式化日期
  const formatDate = (isoString) => {
    const date = new Date(isoString);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  

  // 生成动态分类类型
  const agentTypes = ['全部', ...new Set(agents.map(a => a.agent_type))];

  // 过滤智能体逻辑
  const filteredAgents = agents.filter(agent => {
    const matchesSearch = agent.config.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         agent.config.desc.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesType = selectedType === '全部' || agent.agent_type === selectedType;
    return matchesSearch && matchesType;
  });

  return (
    <div className="w-80 bg-white border-r border-gray-200 flex flex-col relative">
      {/* 右键菜单 */}
      {contextMenu && (
        <div
          ref={menuRef}
          className="absolute z-50 bg-white border border-gray-200 rounded-lg shadow-lg py-2 min-w-[120px] context-menu"
          style={{
            left: Math.min(contextMenu.x, window.innerWidth - 150),
            top: contextMenu.y,
          }}
        >
          <button
            onClick={handleConfigure}
            className="w-full px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 flex items-center gap-2"
          >
            <FontAwesomeIcon icon={faEdit} className="w-4 h-4" />
            <span>编辑</span>
          </button>
          <button
            onClick={handleDelete}
            className="w-full px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2"
          >
            <FontAwesomeIcon icon={faTrashCan} className="w-4 h-4" />
            <span>删除</span>
          </button>
        </div>
      )}

      {/* 选项卡切换 */}
      <div className="flex border-b border-gray-200">
        <button
          onClick={() => setActiveTab('agents')}
          className={`flex-1 p-4 text-sm flex items-center justify-center gap-2 ${
            activeTab === 'agents' 
              ? 'bg-blue-50 text-blue-600 font-semibold' 
              : 'text-gray-600 hover:bg-gray-50'
          }`}
        >
          <FontAwesomeIcon icon={faProjectDiagram} />
          <span>智能体</span>
        </button>
        <button
          onClick={() => setActiveTab('workflows')}
          className={`flex-1 p-4 text-sm flex items-center justify-center gap-2 ${
            activeTab === 'workflows'
              ? 'bg-blue-50 text-blue-600 font-semibold'
              : 'text-gray-600 hover:bg-gray-50'
          }`}
        >
          <FontAwesomeIcon icon={faStream} />
          <span>工作流</span>
        </button>
      </div>

      {activeTab === 'agents' ? (
        <>
          {/* 搜索和过滤区域 */}
          <div className="p-4 border-b border-gray-200">
            <div className="relative mb-4">
              <input 
                type="text" 
                placeholder="搜索智能体" 
                className="w-full px-10 py-2 bg-gray-50 rounded-lg text-sm"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
              <FontAwesomeIcon 
                icon={faSearch} 
                className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" 
              />
            </div>

            <div className="flex flex-wrap gap-2">
              {agentTypes.map((type) => (
                <button 
                  key={type}
                  onClick={() => setSelectedType(type)}
                  className={`px-3 py-1 text-sm rounded-button ${
                    type === selectedType 
                      ? 'bg-blue-500 text-white' 
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  {type}
                </button>
              ))}
            </div>
          </div>

          {/* 智能体列表 */}
          <div className="flex-1 overflow-y-auto p-4 space-y-3">
            {filteredAgents.map((agent) => (
              <div 
                key={agent.id}
                onDoubleClick={() => onConfigureAgent(agent)}
                className="p-3 bg-white border border-gray-200 rounded-lg cursor-move hover:border-blue-500 transition-colors node"
                draggable
                onDragStart={(e) => {
                  e.dataTransfer.setData('agentId', agent.id);
                  e.dataTransfer.setData('agentType', agent.agent_type);
                  e.dataTransfer.effectAllowed = 'move';
                }}
                onContextMenu={(e) => handleRightClick(e, agent, 'agent')}
              >
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                    <FontAwesomeIcon 
                      icon={agent.icon || getIconByType(agent.agent_type)} 
                      className="text-blue-600" 
                    />
                  </div>
                  {/* 添加 flex-1 和 min-w-0 允许内容收缩 */}
                  <div className="flex-1 min-w-0">
                    {/* 标题添加 truncate */}
                    <h3 className="font-medium text-gray-900 truncate">{agent.config.label}</h3>
                    {/* 描述添加 truncate */}
                    <p className="text-sm text-gray-500 truncate">{agent.config.desc}</p>
                    <span className="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full mt-1 inline-block">
                      {agent.agent_type}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      ) : (
        /* 工作流列表 */
        <div className="flex-1 overflow-y-auto p-4">
          <div className="mb-4">
            <h3 className="text-sm font-semibold text-gray-900 mb-2">已保存的工作流</h3>
            <p className="text-xs text-gray-500">
              点击工作流加载到画布，当前保存数：{workflows.length}
            </p>
          </div>

          <div className="space-y-3">
            {workflows.map((workflow) => (
              <div
                key={workflow.id}
                onDoubleClick={() => onLoadWorkflow(workflow)}
                onContextMenu={(e) => handleRightClick(e, workflow, 'workflow')}
                className="p-3 bg-white border border-gray-200 rounded-lg cursor-pointer hover:border-blue-500 transition-colors group"
              >
                <div className="flex justify-between items-start">
                  <div>
                    <h4 className="font-medium text-gray-900 mb-1">{workflow.name}</h4>
                    <div className="flex items-center text-xs text-gray-500">
                      <FontAwesomeIcon icon={faClock} className="mr-1.5" />
                      <span>{formatDate(workflow.updated_at)}</span>
                    </div>
                  </div>
                  <span className="text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity">
                    双击加载
                  </span>
                </div>
                <div className="mt-2 flex items-center text-xs text-gray-400">
                  <span className="mr-2">包含：</span>
                  <span className="bg-gray-100 px-2 py-1 rounded mr-2">
                    {workflow.nodes.length} 个节点
                  </span>
                  <span className="bg-gray-100 px-2 py-1 rounded">
                    {workflow.edges.length} 条连接
                  </span>
                </div>
              </div>
            ))}

            {workflows.length === 0 && (
              <div className="text-center p-6 text-gray-400 text-sm">
                <FontAwesomeIcon icon={faSearch} className="text-2xl mb-2" />
                <p>暂无保存的工作流</p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}